import 'package:crypto/crypto.dart';
import 'package:meco/common/index.dart';
import 'dart:convert';

class UserRepository {
  final DatabaseService _databaseService = DatabaseService();

  // 表名
  final String _tableName = 'users';

  // 密码加密
  String _hashPassword(String password) {
    final bytes = utf8.encode(password);
    final digest = sha256.convert(bytes);
    return digest.toString();
  }

  // 用户注册
  Future<User?> register({
    required String username,
    required String password,
    String? nickname,
    String? email,
  }) async {
    try {
      // 检查用户名是否已存在
      final existingUser = await getUserByUsername(username);
      if (existingUser != null) {
        return null; // 用户名已存在
      }

      final now = DateTime.now();
      final user = User(
        username: username,
        nickname: nickname ?? username, // 默认昵称为用户名
        password: _hashPassword(password), // 加密密码
        avatar: Images.avatar1,
        createdAt: now,
        updatedAt: now,
      );

      final id = await addUser(user);
      return user.copyWith(id: id);
    } catch (e) {
      print('注册错误: $e');
      return null;
    }
  }

  // 用户登录
  Future<User?> login({
    required String username,
    required String password,
  }) async {
    try {
      final db = await _databaseService.database;
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'username = ?',
        whereArgs: [username],
      );

      if (maps.isEmpty) {
        return null; // 用户不存在
      }

      final user = User.fromJson(maps.first);
      final hashedPassword = _hashPassword(password);

      if (user.password != hashedPassword) {
        return null; // 密码错误
      }

      return user;
    } catch (e) {
      print('登录错误: $e');
      return null;
    }
  }

  // 添加用户
  Future<int> addUser(User user) async {
    final db = await _databaseService.database;
    return await db.insert(_tableName, user.toJson());
  }

  // 更新用户
  Future<int> updateUser(User user) async {
    final db = await _databaseService.database;
    return await db.update(
      _tableName,
      user.toJson(),
      where: 'id = ?',
      whereArgs: [user.id],
    );
  }

  // 删除用户
  Future<int> deleteUser(int id) async {
    final db = await _databaseService.database;
    return await db.delete(_tableName, where: 'id = ?', whereArgs: [id]);
  }

  // 获取所有用户
  Future<List<User>> getAllUsers() async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(_tableName);

    return List.generate(maps.length, (i) {
      return User.fromJson(maps[i]);
    });
  }

  // 根据ID获取用户
  Future<User?> getUserById(int id) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      _tableName,
      where: 'id = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return User.fromJson(maps.first);
    }
    return null;
  }

  // 根据用户名获取用户
  Future<User?> getUserByUsername(String username) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      _tableName,
      where: 'username = ?',
      whereArgs: [username],
    );

    if (maps.isNotEmpty) {
      return User.fromJson(maps.first);
    }
    return null;
  }
}
